package com.demo.scenic.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.demo.scenic.common.BaseResponse;
import com.demo.scenic.domain.*;
import com.demo.scenic.domain.dto.UserDTO;
import com.demo.scenic.domain.vo.UserVo;
import com.demo.scenic.mapper.RoleMapper;
import com.demo.scenic.mapper.UserMapper;
import com.demo.scenic.mapper.UserRoleMapper;
import com.demo.scenic.service.UserService;
import com.demo.scenic.shiro.AccountProfile;
import com.demo.scenic.shiro.JwtToken;
import com.demo.scenic.utils.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;


import java.util.*;

@Service
public class UserServiceImpl implements UserService {
    @Value("${image.url}")
    private String imageUrl;

    @Value("${image.avatar}")
    private String avatar;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private  JwtUtils jwtUtils;


    private final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Override
    public User findByMobile(String mobile) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andMobileEqualTo(mobile);
        List<User> userList = userMapper.selectByExample(userExample);
        if (!CollectionUtils.isEmpty(userList)){
            return userList.get(0);
        }
        return null;
    }

    @Override
    public List<Role> findRolesByMobile(String mobile) {
        return null;
    }

    @Override
    public BaseResponse register(UserDTO user) {
        User temp = findByMobile(user.getMobile());
        if (!ObjectUtils.isEmpty(temp)){
            return BaseResponse.fail("该手机号已被注册");
        }

        User users = new User();
        BeanUtil.copyProperties(user,users);

        if (ObjectUtils.isEmpty(user.getAvatar())){
            users.setAvatar(imageUrl + avatar);
        }
        int result = userMapper.insertSelective(users);
        if (result > 0){
            UserRole userRole = new UserRole();
            if (!user.getIdentity().equals("USER") && !user.getIdentity().isEmpty()){
                RoleExample roleExample = new RoleExample();
                roleExample.createCriteria().andRoleNameEqualTo("MERCHANT");
                List<Role> roleList = roleMapper.selectByExample(roleExample);
                if (!CollectionUtils.isEmpty(roleList)){
                    userRole.setRoleId(roleList.get(0).getRoleId());
                    userRole.setUserId(users.getId());
                    userRoleMapper.insertSelective(userRole);
                }
            }

            return BaseResponse.ok("注册成功");
        }
        return BaseResponse.fail("注册失败");
    }

    @Override
    public BaseResponse login(UserDTO user) {
        UserExample userExample = new UserExample();
        userExample.createCriteria().andMobileEqualTo(user.getMobile());
        List<User> userList = userMapper.selectByExample(userExample);
        if (!CollectionUtils.isEmpty(userList)){
            if (userList.get(0).getPassword().equals(user.getPassword())){
                String token = jwtUtils.generateToken(user.getMobile());
                SecurityUtils.getSubject().login(new JwtToken(token));
                return BaseResponse.ok("登录成功",token);
            }
        }
        return BaseResponse.fail("用户不存在");
    }

    @Override
    public BaseResponse getUserInfo(AccountProfile accountProfile) {
        UserVo user = new UserVo();
        BeanUtil.copyProperties(accountProfile,user);
        UserRoleExample userRoleExample = new UserRoleExample();
        userRoleExample.createCriteria().andUserIdEqualTo(accountProfile.getId());
        List<UserRole> userRoleList = userRoleMapper.selectByExample(userRoleExample);
        List<String> roles = new ArrayList<>();
        User users = userMapper.selectByPrimaryKey(accountProfile.getId());
        user.setIdentity(users.getIdentity());
        if (!CollectionUtils.isEmpty(userRoleList)){
            for (UserRole userRole : userRoleList) {
                Role role = roleMapper.selectByPrimaryKey(userRole.getRoleId());
                roles.add(role.getRoleName());
            }
            user.setRole(roles);
        }
        if (!users.getIdentity().equals("USER")&&ObjectUtils.isEmpty(users.getScenicId())){
            return BaseResponse.ok(201,"获取成功",user);
        }
        return BaseResponse.ok(user);
    }

    @Override
    public BaseResponse becomeBusiness(AccountProfile accountProfile) {
        User user = userMapper.selectByPrimaryKey(accountProfile.getId());
        if (user.getIdentity().equals("MERCHANT")){
            return BaseResponse.fail("您已经是商家了");
        }
        RoleExample roleExample = new RoleExample();
        roleExample.createCriteria().andRoleNameEqualTo("MERCHANT");
        List<Role> roleList = roleMapper.selectByExample(roleExample);
        UserRole userRole = new UserRole();
        userRole.setUserId(user.getId());
        userRole.setRoleId(roleList.get(0).getRoleId());
        userRoleMapper.insertSelective(userRole);
        user.setIdentity("ALL");
        userMapper.updateByPrimaryKey(user);
        return BaseResponse.ok("申请成功");
    }

    @Override
    public List<Role> findRolesByUserId(Integer userId) {
        UserRoleExample userRoleExample = new UserRoleExample();
        userRoleExample.createCriteria().andUserIdEqualTo(userId);
        List<UserRole> userRoleList = userRoleMapper.selectByExample(userRoleExample);
        List<Role> roles = new ArrayList<>();
        for (UserRole userRole : userRoleList) {
            Role role = roleMapper.selectByPrimaryKey(userRole.getRoleId());
            roles.add(role);
        }
        return roles;
    }

    @Override
    public BaseResponse updateUserName(AccountProfile accountProfile, String username) {
        User user = userMapper.selectByPrimaryKey(accountProfile.getId());
        user.setUsername(username);
        int judge = userMapper.updateByPrimaryKeySelective(user);
        if (judge > 0){
            return BaseResponse.ok("修改成功");
        }
        return BaseResponse.fail("修改失败");
    }

    @Override
    public BaseResponse updateUserAvatar(AccountProfile accountProfile, String avatar) {
        User user = userMapper.selectByPrimaryKey(accountProfile.getId());
        user.setAvatar(avatar);
        int judge = userMapper.updateByPrimaryKeySelective(user);
        if (judge > 0){
            return BaseResponse.ok("修改成功");
        }
        return BaseResponse.fail("修改失败");
    }

}
